/**
 * @param {number[][]} graph
 * @return {number[]}
 */
var eventualSafeNodes = function (graph) {

  function dfs(index) {
    // 访问过了，就判断是不是安全节点
    if (arr[index] > 0)
      return arr[index] == 2;
    arr[index] = 1;
    for (let j = 0; j < graph[index].length; j++) {
      if (!dfs(graph[index][j])) {
        return false;
      }
    }
    arr[index] = 2;
    return true;
  }

  let row = graph.length;
  let result = [];
  let arr = new Array(row).fill(0);
  for (let i = 0; i < row; i++) {
    if (dfs(i)) {
      result.push(i);
    }
  }
  return result;
};
let graph = [
  [1, 2],
  [2, 3],
  [5],
  [0],
  [5],
  [],
  []
];
console.log(eventualSafeNodes(graph));
graph = [
  [1, 2, 3, 4],
  [1, 2],
  [3, 4],
  [0, 4],
  []
];
console.log(eventualSafeNodes(graph));
